package com.ttx.zookeeper.lock.raw;

import com.ttx.zookeeper.DefaultWatcher;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.ZooKeeper;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static java.util.concurrent.TimeUnit.SECONDS;

/**
 * 共享锁(读写锁)
 * @author TimFruit
 * @date 20-2-28 下午1:13
 */
public class RawSLockWriteLockSample {


    public static void main(String[] args) throws IOException, KeeperException, InterruptedException {
        String connectString="127.0.0.1:2181";

        int timeout=(int)MILLISECONDS.convert(10, SECONDS);


        final ZooKeeper zk=new ZooKeeper(connectString, timeout, new DefaultWatcher(),null);



        String lockPath="/slock";

        if(zk.exists(lockPath,false)==null){
            zk.create(lockPath, "slockNode".getBytes(),ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
        }


        SLock sLock=new SLock(zk, lockPath);



        Lock writeLock=sLock.writeLock();
        System.out.println("准备获取写锁...");
        writeLock.lock();
        System.out.println("获取成功...");

        System.out.println("休眠等待30s...");
        TimeUnit.SECONDS.sleep(30);

        System.out.println("释放写锁...");
        writeLock.unLock();
    }




}
